package com.smartleanx.module.hrm.service.esign.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.smartleanx.framework.common.pojo.CommonResult;
import com.smartleanx.framework.common.pojo.PageResult;
import com.smartleanx.framework.customfield.core.service.bo.CustomFieldDataRespBO;
import com.smartleanx.framework.datapermission.core.annotation.DataPermission;
import com.smartleanx.framework.security.core.util.SecurityFrameworkUtils;
import com.smartleanx.framework.tenant.core.aop.TenantIgnore;
import com.smartleanx.module.bpm.api.v2.BpmNewApi;
import com.smartleanx.module.bpm.api.v2.dto.EsignProcessResult;
import com.smartleanx.module.bpm.api.v2.dto.EsignProcessStartBo;
import com.smartleanx.module.bpm.api.v2.dto.SystemFrameBpmNewVo;
import com.smartleanx.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import com.smartleanx.module.hrm.controller.admin.employee.contract.EmployeeContractRespVO;
import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeDO;
import com.smartleanx.module.hrm.dal.dataobject.esign.ElecCorp;
import com.smartleanx.module.hrm.dal.dataobject.esign.EsignOrgSeal;
import com.smartleanx.module.hrm.dal.dataobject.esign.EsignPsnInfo;
import com.smartleanx.module.hrm.dal.mysql.esign.ElecCorpMapper;
import com.smartleanx.module.hrm.dal.mysql.esign.EsignOrgSealMapper;
import com.smartleanx.module.hrm.dal.mysql.esign.EsignPsnInfoMapper;
import com.smartleanx.module.hrm.enums.ErrorCodeConstants;
import com.smartleanx.module.hrm.eums.employee.EmployeeContractTypeEnum;
import com.smartleanx.module.hrm.service.employee.EmployeeContractService;
import com.smartleanx.module.hrm.service.employee.EmployeeService;
import com.smartleanx.module.hrm.service.esign.ESignUrlConstant;
import com.smartleanx.module.hrm.service.esign.eums.*;
import com.smartleanx.module.hrm.service.esign.service.*;
import com.smartleanx.module.hrm.service.esign.temp.param.ComponentBathParam;
import com.smartleanx.module.hrm.service.esign.temp.param.HrmEContractTaskParam;
import com.smartleanx.module.hrm.service.esign.temp.param.HrmEContractTempParam;
import com.smartleanx.module.hrm.service.esign.temp.po.*;
import com.smartleanx.module.hrm.service.esign.temp.result.*;
import com.smartleanx.module.hrm.service.esign.temp.vo.*;
import com.smartleanx.module.hrm.service.esign.vo.ElecCorpDetailVo;
import com.smartleanx.module.hrm.service.instation.InStationSmsService;
import com.smartleanx.module.hrm.service.instation.InstationSmsTypeEnum;
import com.smartleanx.module.hrm.service.sms.SmsService;
import com.smartleanx.module.hrm.service.sms.SmsTempEnum;
import com.smartleanx.module.hrm.util.FileService;
import com.smartleanx.module.hrm.util.SaasFileUtils;
import com.smartleanx.module.hrm.util.esign.ESignUtil;
import com.smartleanx.module.hrm.util.esign.EsignHttpResponse;
import com.smartleanx.module.hrm.util.esign.FileUtil;
import com.smartleanx.module.hrm.util.esign.enums.EsignRequestType;
import com.smartleanx.module.hrm.util.esign.enums.FileTypeEnums;
import com.smartleanx.module.hrm.util.esign.exception.EsignDemoException;
import com.smartleanx.module.system.api.dept.DeptApi;
import com.smartleanx.module.system.api.dept.PostApi;
import com.smartleanx.module.system.api.dept.PostLevelApi;
import com.smartleanx.module.system.api.dept.dto.DeptRespDTO;
import com.smartleanx.module.system.api.dept.dto.PostLevelRespDTO;
import com.smartleanx.module.system.api.dept.dto.PostRespDTO;
import com.smartleanx.module.system.api.tenant.TenantApi;
import com.smartleanx.module.system.api.tenant.dto.TenantRespDTO;
import com.smartleanx.module.system.api.user.AdminUserApi;
import com.smartleanx.module.system.api.user.dto.AdminUserRespDTO;
import com.tencentcloudapi.ecm.v20190719.models.ISPTypeItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.smartleanx.framework.common.exception.util.ServiceExceptionUtil.exception;

@Service
@Slf4j
public class ESignTaskServiceImpl implements ESignTaskService {

    @Value("${esign.url}")
    private String esignUrl;

    @Autowired
    private HrmEContractTempService hrmEContractTempService;
    @Autowired
    private HrmEContractTempActorsService hrmEContractTempActorsService;
    @Autowired
    private HrmEFolderService hrmEFolderService;
    @Autowired
    private HrmEFolderTempService hrmEFolderTempService;
    @Autowired
    private HrmETempFileService hrmETempFileService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private HrmEContractTaskService hrmEContractTaskService;
    @Autowired
    private HrmEContractTaskActorsService hrmEContractTaskActorsService;
    @Autowired
    private HrmETempComponentsService hrmETempComponentsService;
    @Autowired
    private HrmETaskComponentsService hrmETaskComponentsService;
    @Autowired
    private HrmECustomComponentsService hrmECustomComponentsService;
    @Autowired
    private HrmEFileService hrmEFileService;
    @Autowired
    private HrmETaskFileService hrmETaskFileService;
    @Autowired
    private HrmEEmpComponentsService hrmEEmpComponentsService;
    @Autowired
    private HrmEContractCodeService hrmEContractCodeService;
    @Autowired
    private EsignPsnInfoMapper esignPsnInfoMapper;
    @Autowired
    private ElecCorpMapper elecCorpMapper;
    @Autowired
    private EsignOrgSealMapper esignOrgSealMapper;
    @Autowired
    private TenantApi tenantApi;
    @Autowired
    private DeptApi deptApi;
    @Autowired
    private PostApi postApi;
    @Autowired
    private PostLevelApi postLevelApi;
    @Autowired
    private BpmNewApi bpmNewApi;
    @Autowired
    private FileService fileService;
    @Autowired
    private ContractPackageService contractPackageService;
    @Autowired
    private EmployeeContractService employeeContractService;
    @Autowired
    private InStationSmsService inStationSmsService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private AdminUserApi adminUserApi;


    @Override
    public JSONObject getFillInLink(FillInLinkVo fillInLinkVo) {
        String apiaddr= ESignUrlConstant.TEMPLATE_FILL_URL;
        //请求方法
        EsignRequestType requestType= EsignRequestType.POST;

        //获取文件id以及文件上传地址

        JSONObject parram = new JSONObject();
        parram.set("docTemplateId",fillInLinkVo.getDocTemplateId());

        JSONArray componentFillingtValues = new JSONArray();
        JSONObject item = new JSONObject();
        item.set("componentId","4834d3c3a87d4baf9ce4ee0fbe384f4f");
        item.set("componentValue","自动回显");
        componentFillingtValues.add(item);
        parram.set("componentFillingtValues",componentFillingtValues);
        String jsonParm=parram.toString();


        EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
        JsonObject data = jsonObject.getAsJsonObject("data");
        JSONObject result = new JSONObject();
        result.set("url",data.get("docTemplateFillLongUrl").getAsString());
        return result;
    }

    @Override
    public ComponentResult getFillInComponents(Long taskId, String fillInType) {
        ComponentResult componentResult = new ComponentResult();
        //1. 获取任务信息
        HrmEContractTask hrmEContractTask = hrmEContractTaskService.getById(taskId);
        componentResult.setContractName(hrmEContractTask.getContractName());
        //2. 获取模板控件
        List<HrmETaskComponents> fillInComponents = hrmETaskComponentsService.getFillInComponentsComponentIdIsNotNull(taskId);
        Integer fillInUpdate = 1;

        //3. 获取模板填写顺序   仅支持最多企业员工双方 填写的情况下
//        HrmEContractTemp contractTemp = hrmEContractTempService.getById(hrmEContractTask.getTempId());
        List<HrmEContractTempActors> actorList = hrmEContractTempActorsService.getTempActorsByTempId(hrmEContractTask.getTempId(),true);
        HrmEContractTempActors hrmEContractTempActors = actorList.stream().filter(p ->p.getActorType().equals(fillInType) ).findAny().orElse(null);
        //3.1 没有填写权限
        List<HrmEContractTaskActors> taskActorList = hrmEContractTaskActorsService.getTaskActorListByTaskId(taskId);
        if(hrmEContractTempActors.getActorFillInPermission().equals("0")){
            fillInUpdate = 0;
        }else{
            //3.2 排序权限  数字越小优先级越高，1是最小， 如果不是1  需要判断上一位是否填写完成
            if(hrmEContractTempActors.getActorFillInSort() != 1){
                HrmEContractTaskActors hrmEContractTaskActors = taskActorList.stream().filter(p -> !p.getActorType().equals(fillInType)).findAny().orElse(null);
                //3.3 上一位参与方还未填写完成
                if(hrmEContractTaskActors.getFillStatus() == 0){
                    fillInUpdate = 0;
                }
            }
        }
        //4. 获取填写控件
        List<HrmECustomComponents> componentsList = hrmECustomComponentsService.getComponentsCustomList();
        Map<String, HrmECustomComponents> componentsMap = componentsList.stream().collect(Collectors.toMap(HrmECustomComponents::getComponentId, Function.identity()));
        Integer finalFillInUpdate = fillInUpdate;
        HrmEContractTaskActors hrmEContractTaskActors = taskActorList.stream().filter(t -> t.getActorType().equals(ActorTypeEnum.PERSON.getCode())).findAny().orElse(null);
        List<List<CustomFieldDataRespBO>> empDataList = new ArrayList<>();
        //1. 调用花名册接口 1 1,  1 2 ,1 3,2 4
        try {
            empDataList.addAll(employeeService.getEmployeeField(hrmEContractTaskActors.getEmpId(), 1, 1));
            empDataList.addAll(employeeService.getEmployeeField(hrmEContractTaskActors.getEmpId(), 1, 2));
            empDataList.addAll(employeeService.getEmployeeField(hrmEContractTaskActors.getEmpId(), 1, 3));
            empDataList.addAll(employeeService.getEmployeeField(hrmEContractTaskActors.getEmpId(), 2, 4));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        List<ComponentResult.Component> componentList = fillInComponents.stream().map(p -> {
            ComponentResult.Component component = new ComponentResult.Component();
            BeanUtil.copyProperties(p, component);
            //做回显数据处理
            if(StrUtil.isNotBlank(p.getOriginCustomComponentId())){
                HrmECustomComponents hrmECustomComponents = componentsMap.get(p.getOriginCustomComponentId());
                try {
                    if(StrUtil.isNotBlank(p.getComponentValue())){
                        component.setComponentValue(p.getComponentValue());
                    }else{
                        component.setComponentValue(getComponentValue(hrmECustomComponents,empDataList));
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            boolean fileInUpdate = StrUtil.isNotBlank(component.getComponentValue()) && (hrmEContractTask.getTaskStatus() - TaskStatusEnum.CREATE_ING.getCode() != 0);
            component.setFillInUpdate(fileInUpdate?0:finalFillInUpdate);
            return component;
        }).collect(Collectors.toList());
        componentResult.setComponentList(componentList);

        return componentResult;
    }

    //获取回现数据
    public String getComponentValue(HrmECustomComponents hrmECustomComponents,List<List<CustomFieldDataRespBO>> empDataList) throws IllegalAccessException {
        for (List<CustomFieldDataRespBO> customDataList : empDataList) {
            for (CustomFieldDataRespBO customItem : customDataList) {
                String componentKey = hrmECustomComponents.getComponentKey();
                if(Long.parseLong(componentKey) == customItem.getFieldId()){
                    System.out.println(customItem.getFieldValue());
                    if(StrUtil.isEmpty(customItem.getFieldValue())){
                        return "";
                    }
                    if(customItem.getType() == 7){
                        com.alibaba.fastjson2.JSONArray jsonArray = JSON.parseArray(customItem.getOptions());
                        for (Object o : jsonArray) {
                            com.alibaba.fastjson2.JSONObject from = com.alibaba.fastjson2.JSONObject.from(o);
                            if(from.get("value").toString().equals(customItem.getFieldValue())){
                                return from.get("label").toString();
                            }
                        }
                        return "";
                    }else if(customItem.getName().contains("日期")){
                        DateTime date = DateUtil.date(Long.parseLong(customItem.getFieldValue()));
                        return DateUtil.format(date,DatePattern.NORM_DATETIME_PATTERN);
                    }else if("部门".equals(customItem.getName())){
                        CommonResult<DeptRespDTO> dept = deptApi.getDept(Long.parseLong(customItem.getFieldValue()));
                        return dept.getData().getName();
                    }else if("岗位".equals(customItem.getName())){
                        CommonResult<PostRespDTO> post = postApi.getPost(Long.parseLong(customItem.getFieldValue()));
                        return post.getData().getName();
                    }else if("职级".equals(customItem.getName())){
                        CommonResult<PostLevelRespDTO> postLevelById = postLevelApi.getPostLevelById(Long.parseLong(customItem.getFieldValue()));
                        return postLevelById.getData().getName();
                    }else if("直属上级".equals(customItem.getName())){
                        CommonResult<AdminUserRespDTO> user = adminUserApi.getUser(Long.parseLong(customItem.getFieldValue()));
                        return user.getData().getNickname();
                    }
                    return customItem.getFieldValue();
                }
            }
        }


//        if(CustomComponentsEnum.EMP_NAME.getCode().equals(hrmECustomComponents.getComponentKey())){
//            return employee.getName();
//        }
//        if(CustomComponentsEnum.EMP_PHONE.getCode().equals(hrmECustomComponents.getComponentKey())){
//            return employee.getMobile();
//        }
//        if(CustomComponentsEnum.EMP_CORP.getCode().equals(hrmECustomComponents.getComponentKey())){
//            CommonResult<TenantRespDTO> tenant = tenantApi.getTenant(employee.getTenantId());
//            return tenant.getData().getName();
//        }
//        if(CustomComponentsEnum.EMP_AGE.getCode().equals(hrmECustomComponents.getComponentKey())){
//            if(employee.getDateOfBirth() != null){
//                int age = DateUtil.age(DateUtil.parse(DateUtil.format(employee.getDateOfBirth(), DatePattern.NORM_DATETIME_PATTERN)), DateUtil.date());
//                return age+"";
//            }
//            return null;
//        }
//        if(CustomComponentsEnum.EMP_CARD_ID.getCode().equals(hrmECustomComponents.getComponentKey())){
//            if(employee.getIdNumber() != null){
//                return employee.getIdNumber();
//            }
//            return null;
//        }
//        if(CustomComponentsEnum.EMP_SEX.getCode().equals(hrmECustomComponents.getComponentKey())){
//            if(employee.getSex() != null){
//                return employee.getSex() == 1?"男":"女";
//            }
//            return null;
//        }
//        if(CustomComponentsEnum.EMP_ADDRESS.getCode().equals(hrmECustomComponents.getComponentKey())){
//            if(employee.getNativePlace() != null){
//                return employee.getNativePlace();
//            }
//            return null;
//        }
//        if(CustomComponentsEnum.EMP_NO.getCode().equals(hrmECustomComponents.getComponentKey())){
//            if(employee.getEmployeeNo() != null){
//                return employee.getEmployeeNo();
//            }
//            return null;
//        }
//        if(CustomComponentsEnum.EMP_DEP.getCode().equals(hrmECustomComponents.getComponentKey())){
//            CommonResult<DeptRespDTO> dept = deptApi.getDept(employee.getDeptId());
//            return dept.getData().getName();
//        }
//        if(CustomComponentsEnum.EMP_POST.getCode().equals(hrmECustomComponents.getComponentKey())){
//            CommonResult<PostRespDTO> post = postApi.getPost(employee.getPostId());
//            return post.getData().getName();
//        }

        return null;
    }

    @Override
    public String getFillInViewToPDF(HashMap<String,Object> map) {
        Long taskId = Long.parseLong(map.get("taskId").toString());
        map.remove("taskId");
        HrmEContractTask contractTask = hrmEContractTaskService.getById(taskId);
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(contractTask.getTempId());
        List<HrmETaskComponents> fillInComponents = hrmETaskComponentsService.getFillInComponents(taskId);
        Map<Long, HrmETaskComponents> componentsMap = fillInComponents.stream().collect(Collectors.toMap(HrmETaskComponents::getId, Function.identity()));
        String apiaddr=ESignUrlConstant.TEMPLATE_TO_PDF;
        String tempId = contractTemp.getTempEsignId();
        String fileName = UUID.randomUUID().toString();
        //请求方法
        EsignRequestType requestType= EsignRequestType.POST;

        //获取文件id以及文件上传地址
        JSONObject parram = new JSONObject();
        parram.set("docTemplateId",tempId);
        parram.set("fileName",fileName);
        JSONArray components = new JSONArray();
        for (String key : map.keySet()) {
            HrmETaskComponents hrmETaskComponents = componentsMap.get(Long.parseLong(key));
            if(hrmETaskComponents == null ||(hrmETaskComponents.getComponentId() == null && hrmETaskComponents.getComponentKey() == null)){
                continue;
            }
            JSONObject comItem = new JSONObject();
            comItem.set("componentId",hrmETaskComponents.getComponentId());
            comItem.set("componentKey",hrmETaskComponents.getComponentKey());
            comItem.set("componentValue",map.get(key) != null ?map.get(key):"--");
            components.add(comItem);
        }
//        for (HrmETaskComponents component : componentList) {
//            HrmETaskComponents hrmETaskComponents = componentsMap.get(component.getId());
//            if(hrmETaskComponents == null ||(hrmETaskComponents.getComponentId() == null && hrmETaskComponents.getComponentKey() == null)){
//                continue;
//            }
//            JSONObject comItem = new JSONObject();
//            comItem.set("componentId",hrmETaskComponents.getComponentId());
//            comItem.set("componentKey",hrmETaskComponents.getComponentKey());
//            comItem.set("componentValue",StrUtil.isNotBlank(component.getComponentValue())?component.getComponentValue():"--");
//            components.add(comItem);
//        }

        parram.set("components",components);
        parram.set("requiredCheck",false);
        String jsonParm=parram.toString();



        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
            if(jsonObject.get("code").getAsInt() != 0){
                throw exception(jsonObject.get("code").getAsInt(),jsonObject.get("message").getAsString());
            }
//          // 转文件  获取文件地址
            return FileUtil.getFileHTMLFileDownloadUrl(jsonObject.get("data").getAsJsonObject().get("fileId").getAsString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public String getFillInViewDetail(Long taskId) {
        HrmEContractTask contractTask = hrmEContractTaskService.getById(taskId);
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(contractTask.getTempId());
        List<HrmETaskComponents> fillInComponents = hrmETaskComponentsService.getFillInComponents(taskId);

        String apiaddr=ESignUrlConstant.TEMPLATE_TO_PDF;
        String tempId = contractTemp.getTempEsignId();
        String fileName = UUID.randomUUID().toString();
        //请求方法
        EsignRequestType requestType= EsignRequestType.POST;
        //获取文件id以及文件上传地址
        JSONObject parram = new JSONObject();
        parram.set("docTemplateId",tempId);
        parram.set("fileName",fileName);

        JSONArray components = new JSONArray();
        for (HrmETaskComponents hrmETaskComponents : fillInComponents) {
            if(hrmETaskComponents == null ||(hrmETaskComponents.getComponentId() == null && hrmETaskComponents.getComponentKey() == null)){
                continue;
            }
            JSONObject comItem = new JSONObject();
            comItem.set("componentId",hrmETaskComponents.getComponentId());
            comItem.set("componentKey",hrmETaskComponents.getComponentKey());
            comItem.set("componentValue",StrUtil.isNotBlank(hrmETaskComponents.getComponentValue()) ?StrUtil.isNotBlank(hrmETaskComponents.getComponentValue()):"--");
            components.add(comItem);
        }

        parram.set("components",components);
        parram.set("requiredCheck",false);
        String jsonParm=parram.toString();

        JsonObject jsonObject = null;
        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            Gson gson = new Gson();
            jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        if(jsonObject.get("code").getAsInt() != 0){
            throw exception(jsonObject.get("code").getAsInt(),jsonObject.get("message").getAsString());
        }
//          // 转文件  获取文件地址
        try {
            return FileUtil.getFileHTMLFileDownloadUrl(jsonObject.get("data").getAsJsonObject().get("fileId").getAsString());
        } catch (EsignDemoException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getFillInToPDFId(Long taskId, List<HrmETaskComponents> componentList) {
        HrmEContractTask contractTask = hrmEContractTaskService.getById(taskId);
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(contractTask.getTempId());
        List<HrmETaskComponents> fillInComponents = hrmETaskComponentsService.getFillInComponents(taskId);
        System.out.println("============componentsList=================");
        System.out.println(componentList.toString());
        System.out.println("============fillInComponents===============");
        System.out.println(fillInComponents.toString());
        Map<Long, HrmETaskComponents> componentsMap = fillInComponents.stream().collect(Collectors.toMap(HrmETaskComponents::getId, Function.identity()));
        String apiaddr=ESignUrlConstant.TEMPLATE_TO_PDF;
        String tempId = contractTemp.getTempEsignId();
        String fileName = UUID.randomUUID().toString();
        //请求方法
        EsignRequestType requestType= EsignRequestType.POST;

        //获取文件id以及文件上传地址
        JSONObject parram = new JSONObject();
        parram.set("docTemplateId",tempId);
        parram.set("fileName",fileName);
        JSONArray components = new JSONArray();
        for (HrmETaskComponents component : componentList) {
            JSONObject comItem = new JSONObject();
            HrmETaskComponents hrmETaskComponents = componentsMap.get(component.getId());
            if(hrmETaskComponents.getComponentId() == null && hrmETaskComponents.getComponentKey() ==null){
                continue;
            }
            comItem.set("componentId",hrmETaskComponents.getComponentId());
            comItem.set("componentKey",hrmETaskComponents.getComponentKey());
            comItem.set("componentValue",component.getComponentValue());
            components.add(comItem);
        }

        System.out.println("============components上传===============");
        System.out.println(components.toString());
        parram.set("components",components);
        parram.set("requiredCheck",false);
        String jsonParm=parram.toString();


        EsignHttpResponse esignHttpResponse = null;
        try {
            esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);

        } catch (Exception e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
        if(jsonObject.get("code").getAsInt() == ErrorCodeConstants.E_SIGN_COMPONENT_IS_NULL.getCode()){
            throw exception(ErrorCodeConstants.E_SIGN_COMPONENT_IS_NULL);
        }
        return jsonObject.get("data").getAsJsonObject().get("fileId").getAsString();
    }

    @Override
    public PageResult<HrmETaskListResult> getTaskPage(HrmEContractTaskParam param) {
        return hrmEContractTaskService.getTaskPage(param);
    }

    @Override
    public EsignHttpResponse getHTMLDetail(String fileId) {
        String apiaddr= String.format(ESignUrlConstant.PDF_FILL_IN_PDF,fileId);
        System.out.println(apiaddr);
        //请求方法
        EsignRequestType requestType= EsignRequestType.GET;

        //获取文件id以及文件上传地址

        JSONObject parram = new JSONObject();
        String jsonParm=parram.toString();


        //生成签名鉴权方式的的header
        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            System.out.println(esignHttpResponse.getBody());
            return esignHttpResponse;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public EsignHttpResponse getTemplateDetail(String docTemplateId) {
        String apiaddr= String.format(ESignUrlConstant.DOC_TEMPLATE_DETAIL,docTemplateId);
        System.out.println(apiaddr);
        //请求方法
        EsignRequestType requestType= EsignRequestType.GET;

        //获取文件id以及文件上传地址

        JSONObject parram = new JSONObject();
        String jsonParm=parram.toString();


        //生成签名鉴权方式的的header
        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            System.out.println(esignHttpResponse.getBody());
            return esignHttpResponse;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFillInData(FillInViewPDFLinkVo fillInViewPDFLinkVo,String contractName,String contractCode) {
        List<HrmETaskComponents> componentList = fillInViewPDFLinkVo.getComponentList();
        Integer saveType = fillInViewPDFLinkVo.getSaveType();
        Long taskId = fillInViewPDFLinkVo.getTaskId();
        String actorType = fillInViewPDFLinkVo.getActorType();
        //1. 保存填写数据
        hrmETaskComponentsService.updateBatchById(componentList);
        //2. 改变任务状态
        HrmEContractTask contractTask = hrmEContractTaskService.getById(taskId);
        if(StrUtil.isNotBlank(contractName)){
            contractTask.setContractName(contractName);
        }
        if(StrUtil.isNotBlank(contractCode)){
            contractTask.setContractCode(contractCode);
        }
        HrmEContractTaskActors hrmEContractTaskActors = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, actorType);
        List<HrmEContractTempActors> tempActorsList = hrmEContractTempActorsService.getTempActorsByTempId(contractTask.getTempId());
        //2.1 企业填写或暂存
        if(ActorTypeEnum.CORP.getCode().equals(actorType)){
            //2.1.1 填写权限，填写顺序，是否填写   填写状态为1  暂存  则为创建中
            Integer taskStatus = saveType;
            HrmEContractTempActors personActor = tempActorsList.stream().filter(p -> p.getActorType().equals(ActorTypeEnum.PERSON.getCode())).findAny().orElse(null);
            if(saveType != 1){
                //2.1.2 有权限
                taskStatus = TaskStatusEnum.AWAIT_VIEW.getCode();
                //2.1.3 员工是否有填写权限
                if(personActor == null || "0".equals(personActor.getActorFillInPermission())){
                    taskStatus = TaskStatusEnum.FILL_IN_ACC.getCode();
                }
                //2.1.4 员工已填写
                HrmEContractTaskActors personTaskActors = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.PERSON.getCode());
                if(personActor == null || 1 == personTaskActors.getFillStatus()){
                    taskStatus = TaskStatusEnum.FILL_IN_ACC.getCode();
                }

            }
            contractTask.setTaskStatus(taskStatus);
        }else if(ActorTypeEnum.PERSON.getCode().equals(actorType)){
            //2.2 个人保存  hrmEContractTaskActors 是个人参与方信息
            HrmEContractTempActors corpActors = tempActorsList.stream().filter(p -> p.getActorType().equals(actorType)).findAny().orElse(null);
            Integer taskStatus = TaskStatusEnum.FILL_IN_ACC.getCode();
            //2.2.1 有企业参与方 且 企业有填写权限 且 员工先填
            if(corpActors!= null && "1".equals(corpActors.getActorFillInPermission())){
                taskStatus = hrmEContractTaskActors.getActorFillInSort() == 1?TaskStatusEnum.AWAIT_FILL_IN_CORP.getCode():TaskStatusEnum.FILL_IN_ACC.getCode();
            }
            contractTask.setTaskStatus(taskStatus);
        }
        //3. 改变填写状态
        if(saveType != 1){
            hrmEContractTaskActors.setFillStatus(1);
            hrmEContractTaskActors.setActorFillInTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        }
        hrmEContractTaskActorsService.updateById(hrmEContractTaskActors);
        hrmEContractTaskService.updateById(contractTask);
        if(ActorTypeEnum.CORP.getCode().equals(actorType)){
            System.out.println("=======填写短信发送");
            // 发送站内消息通知 和 短信通知
            HrmEContractTempActors personActor = tempActorsList.stream().filter(p -> p.getActorType().equals(ActorTypeEnum.PERSON.getCode())).findAny().orElse(null);
            if(personActor != null && "1".equals(personActor.getActorFillInPermission())){
                inStationSmsService.sendInstationSms(contractTask.getId(), InstationSmsTypeEnum.FILLIN.getCode());
                HrmEContractTaskActors personTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.PERSON.getCode());
                HrmEContractTaskActors corpTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.CORP.getCode());

                JSONObject jsonObject = new JSONObject();
                jsonObject.set("name",corpTaskActor.getActorName());
                jsonObject.set("contractName",contractTask.getContractName());
                jsonObject.set("code",0);
                smsService.sendSignSms(personTaskActor.getPsnAccount(),SmsTempEnum.FILLIN.getCode(),jsonObject);
            }
        }
        if(ActorTypeEnum.PERSON.getCode().equals(actorType)){
            HrmEContractTempActors corpActor = tempActorsList.stream().filter(p -> p.getActorType().equals(ActorTypeEnum.CORP.getCode())).findAny().orElse(null);
            if(corpActor != null && "1".equals(corpActor.getActorFillInPermission())){
                HrmEContractTaskActors corpTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.CORP.getCode());
                //未填写 发送消息
                if(corpTaskActor.getFillStatus() != 1){
                    smsService.sendFillInsationAndSms(taskId,InstationSmsTypeEnum.CONTRACT_FILLIN_SYSTEM.getCode());
                }
            }

        }

        //4. 双方都提交填写后  发起签署 或者 等待审批   修改任务状态
        if(TaskStatusEnum.FILL_IN_ACC.getCode() == contractTask.getTaskStatus()){
            //获取PDF文件id
            componentList = componentList.stream().filter(p -> StrUtil.isNotBlank(p.getComponentId())).collect(Collectors.toList());
            String fillInToPDFId = getFillInToPDFId(taskId, componentList);
            contractTask.setFilePdfId(fillInToPDFId);
            hrmEContractTaskService.updateById(contractTask);
            //2.获取预览文件地址
            EsignHttpResponse htmlDetail = getHTMLDetail(fillInToPDFId);
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(htmlDetail.getBody(), JsonObject.class);
            int asInt = jsonObject.get("data").getAsJsonObject().get("fileStatus").getAsInt();
            String uploadUrl = "";
            if(asInt == 2){
                String downloadUrl = jsonObject.get("data").getAsJsonObject().get("fileDownloadUrl").getAsString();
                File localFile = SaasFileUtils.getNetUrlHttp(downloadUrl);
                uploadUrl = fileService.upload(localFile);
            }
            //3. 发起审批流程
            HrmEContractTemp contractTemp = hrmEContractTempService.getById(contractTask.getTempId());
            EsignProcessStartBo esignProcessStartBo = new EsignProcessStartBo();
            esignProcessStartBo.setTemplateKey(contractTemp.getLabourContract() == 1?"ELEC_LABOR":"ELEC_OTHER");
            com.alibaba.fastjson2.JSONObject jsonObject1 = new com.alibaba.fastjson2.JSONObject();
            jsonObject1.put("uploadUrl",uploadUrl);
            esignProcessStartBo.setFileInfo(jsonObject1);
            esignProcessStartBo.setElecLaborOrgId(contractTask.getCorpId().intValue());
            ElecCorp elecCorp = elecCorpMapper.selectById(contractTask.getCorpId());
            esignProcessStartBo.setElecLaborOrg(elecCorp.getCorpName());
            HrmEContractTaskActors personTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.PERSON.getCode());
            esignProcessStartBo.setElecLaborUser(Collections.singletonList(SystemFrameBpmNewVo.builder().id(personTaskActor.getEmpId()).name(personTaskActor.getActorName()).type("user").build()));
            EmployeeDO employee = employeeService.getEmployeeById(personTaskActor.getEmpId());
            CommonResult<DeptRespDTO> dept = deptApi.getDept(employee.getDeptId());
            esignProcessStartBo.setElecLaborDept(Collections.singletonList(SystemFrameBpmNewVo.builder().id("d"+employee.getDeptId()).name(dept.getData().getName()).type("dept").build()));
            if(contractTemp.getLabourContract() == 1){
                List<HrmETaskComponents> componentsList = hrmETaskComponentsService.getFillInComponentsComponentIdIsNull(contractTask.getId());
                for (HrmETaskComponents hrmETaskComponents : componentsList) {
                    if("contract_type".equals(hrmETaskComponents.getColumnCode())){
                        esignProcessStartBo.setElecLaborContractType(EmployeeContractTypeEnum.getName(Integer.parseInt(hrmETaskComponents.getComponentValue())));
                    }else if("contract_time".equals(hrmETaskComponents.getColumnCode())){
                        esignProcessStartBo.setElecLaborDuration(Integer.parseInt(hrmETaskComponents.getComponentValue()));
                    }else if("contract_start_time".equals(hrmETaskComponents.getColumnCode())){
                        esignProcessStartBo.setElecLaborStartDate(hrmETaskComponents.getComponentValue());
                    }else if("contract_end_time".equals(hrmETaskComponents.getColumnCode())){
                        esignProcessStartBo.setElecLaborEndDate(hrmETaskComponents.getComponentValue());
                    }
                    if(esignProcessStartBo.getElecLaborSignDate() == null && esignProcessStartBo.getElecLaborStartDate() != null && esignProcessStartBo.getElecLaborDuration() != null){
                        DateTime dateTime = DateUtil.offsetMonth(DateUtil.parseDate(esignProcessStartBo.getElecLaborStartDate()), 12 * esignProcessStartBo.getElecLaborDuration());
                        esignProcessStartBo.setElecLaborSignDate(DateUtil.format(dateTime,DatePattern.NORM_DATE_PATTERN));
                    }
                }
            }
            HrmEContractTaskActors corpTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.CORP.getCode());
            EmployeeDO employee1 = employeeService.getEmployeeById(corpTaskActor.getEmpId());
            CommonResult<AdminUserRespDTO> user = adminUserApi.getUser(employee1.getUserId());
            esignProcessStartBo.setStartUserId(user.getData().getId());
            esignProcessStartBo.setStartUserName(user.getData().getNickname());

            CommonResult<EsignProcessResult> esignProcessResultCommonResult = bpmNewApi.esignProcessStart(esignProcessStartBo);
            EsignProcessResult data = esignProcessResultCommonResult.getData();

            // 判断是否要 发起签署
            if(!data.isBpmEnable()){
                createTaskSignFlowByTaskId(taskId);
            }else if(!data.isBpmConfigStatus()){
                //抛出异常
                log.error("审批未配置校验 为：false");
            }else{
                contractTask.setBpmProcessId(data.getProcessInstanceId());
                contractTask.setApprovalStatus(BpmProcessInstanceStatusEnum.RUNNING.getStatus());
                hrmEContractTaskService.updateById(contractTask);
            }
        }


    }

    @Override
    public void saveFillInDataBath(ComponentBathResult param) {
        List<Map<Object, Object>> columnValueMap = param.getColumnValueMap();
        String taskId1 = columnValueMap.get(0).get("taskId").toString();
        HrmEContractTask contractTask = hrmEContractTaskService.getById(taskId1);
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(contractTask.getTempId());
        bpmNewApi.processCheck(contractTemp.getLabourContract() == 1?"ELEC_LABOR":"ELEC_OTHER");
        //1.发起的是劳动合同 需要判断员工是否存在已有的合同

        List<ComponentBathResult.ColumnValue> columnValueList = param.getColumnValueList();


        for (ComponentBathResult.ColumnValue columnValue : columnValueList) {
            for (Map<Object, Object> objectObjectMap : columnValueMap) {
                if (objectObjectMap.get("taskId").toString().equals(columnValue.getTaskId().toString())){
                    String value =  objectObjectMap.get(columnValue.getColumnId().toString()) ==null?null:objectObjectMap.get(columnValue.getColumnId().toString()).toString();
                    columnValue.setColumnValue(value);
                }
            }
        }
        Map<Long, List<ComponentBathResult.ColumnValue>> taskMap = columnValueList.stream().collect(Collectors.groupingBy(ComponentBathResult.ColumnValue::getTaskId));

        for (Long taskId : taskMap.keySet()) {
            FillInViewPDFLinkVo fillInViewPDFLinkVo = new FillInViewPDFLinkVo();
            fillInViewPDFLinkVo.setTaskId(taskId);
            fillInViewPDFLinkVo.setActorType("1");
            fillInViewPDFLinkVo.setSaveType(param.getSaveType());

            List<ComponentBathResult.ColumnValue> columnValues = taskMap.get(taskId);
            AtomicReference<String> contractName = new AtomicReference<>("");
            AtomicReference<String> contractCode = new AtomicReference<>("");
            AtomicReference<String> contractStartTime = new AtomicReference<>("");
            AtomicReference<String> contractTime = new AtomicReference<>("");
            List<HrmETaskComponents> collect = columnValues.stream().map(p -> {
                HrmETaskComponents hrmETaskComponents = new HrmETaskComponents();
                hrmETaskComponents.setId(p.getTaskColumnId());
                hrmETaskComponents.setComponentValue(p.getColumnValue());
                hrmETaskComponents.setFillInType(param.getFillInType());
                if("contract_name".equals(p.getColumnCode())){
                    contractName.set(p.getColumnValue());
                }
                if("contract_code".equals(p.getColumnCode())){
                    contractCode.set(p.getColumnValue());
                }
                if("contract_start_time".equals(p.getColumnCode())){
                    contractStartTime.set(p.getColumnValue());
                }
                if("contract_time".equals(p.getColumnCode())){
                    contractTime.set(p.getColumnValue());
                }
                return hrmETaskComponents;
            }).collect(Collectors.toList());

            if(contractTemp.getLabourContract() == 1){
                HrmEContractTaskActors personTaskActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.PERSON.getCode());
                List<EmployeeContractRespVO> employeeContractList = employeeContractService.getEmployeeContractList(personTaskActor.getEmpId());
                if(CollUtil.isNotEmpty(employeeContractList)){
                    for (EmployeeContractRespVO employeeContractRespVO : employeeContractList) {
                        LocalDateTime startTime = LocalDate.parse(contractStartTime.get()).atStartOfDay();
                        if( startTime.isAfter(employeeContractRespVO.getStartTime()) && startTime.isBefore(employeeContractRespVO.getEndTime())){
                            throw exception(ErrorCodeConstants.EMP_CONTR_IS_NOT_NULL);
                        }
                        DateTime time = DateUtil.offsetMonth(DateUtil.date(startTime), 12 * Integer.parseInt(contractTime.get()));
                        String format = DateUtil.format(time, DatePattern.NORM_DATE_PATTERN);
                        LocalDateTime endTime = LocalDate.parse(format).atStartOfDay();
                        if( endTime.isAfter(employeeContractRespVO.getStartTime()) && endTime.isBefore(employeeContractRespVO.getEndTime())){
                            throw exception(ErrorCodeConstants.EMP_CONTR_IS_NOT_NULL);
                        }
                    }
                }
            }
            fillInViewPDFLinkVo.setComponentList(collect);
            saveFillInData(fillInViewPDFLinkVo,contractName.get(),contractCode.get());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createSignFlow(SignFlowParamVo signFlowParamVo) {
        //1. 校验员工是否存在
        Long empId = signFlowParamVo.getEmpId();
//        if(null == empId){
//            throw exception(ErrorCodeConstants.USER_IS_NULL_ERROR);
//        }
        EmployeeDO employee = employeeService.getEmployeeById(empId);
        EmployeeDO corpEmp = employeeService.getEmployeeByUserId(SecurityFrameworkUtils.getLoginUserId());

        //2. 保留数据还未发起
        HrmEContractTask hrmEContractTask = new HrmEContractTask();
        hrmEContractTask.setDataStatus(1);
        hrmEContractTask.setTempId(signFlowParamVo.getTempId());
        hrmEContractTask.setTaskStatus(0);
        hrmEContractTask.setContractName(signFlowParamVo.getContractName());
        hrmEContractTask.setContractDesc(signFlowParamVo.getContractDesc());
        hrmEContractTask.setContractCode(signFlowParamVo.getContractCode());
        hrmEContractTask.setCorpId(signFlowParamVo.getCorpId());
        hrmEContractTask.setId(signFlowParamVo.getTaskId());
        hrmEContractTask.setCreator(corpEmp.getName());
        //2.1 获取模板数据
        HrmEContractTemp hrmEContractTemp = hrmEContractTempService.getById(signFlowParamVo.getTempId());

        hrmEContractTask.setFileId(hrmEContractTemp.getTempEsignFileId());
        hrmEContractTask.setESignTempId(hrmEContractTemp.getTempEsignId());
        hrmEContractTask.setDeptId(corpEmp.getDeptId());
        hrmEContractTask.setUserId(corpEmp.getUserId());
        hrmEContractTask.setDeleted(false);

        if(hrmEContractTemp.getSignTime() != 0){
            hrmEContractTask.setEffectiveDuration(DateUtil.offsetDay(DateUtil.date(), hrmEContractTemp.getSignTime()));
        }

//        if(hrmEContractTask.getCreateTime() == null){
//            hrmEContractTask.setCreateTime(LocalDateTime.now());
//        }
        hrmEContractTaskService.saveOrUpdate(hrmEContractTask);

        if(signFlowParamVo.getTaskId() != null){
            return signFlowParamVo.getTaskId();
        }

        //2.2 添加任务参与方
        List<HrmEContractTempActors> tempActorList = hrmEContractTempActorsService.getTempActorsByTempId(signFlowParamVo.getTempId());
        ArrayList<HrmEContractTaskActors> actorList = new ArrayList<>();
        for (HrmEContractTempActors actor : tempActorList) {
            if(ActorTypeEnum.CORP.getCode().equals(actor.getActorType())){
                if(hrmEContractTemp.getSealFallType() != null && hrmEContractTemp.getSealFallType() == 2){
                    continue;
                }
            }

            HrmEContractTaskActors hrmEContractTaskActors = new HrmEContractTaskActors();
            String actorName = actor.getActorType().equals(ActorTypeEnum.CORP.getCode())?ActorTypeEnum.CORP.getDesc():ActorTypeEnum.PERSON.getDesc();
            BeanUtil.copyProperties(actor,hrmEContractTaskActors);
            hrmEContractTaskActors.setId(null);
            hrmEContractTaskActors.setDataStatus(1);
            hrmEContractTaskActors.setTaskId(hrmEContractTask.getId());
            hrmEContractTaskActors.setActorId(actorName);
            hrmEContractTaskActors.setActorType(actor.getActorType());
            hrmEContractTaskActors.setReadStatus(0);
            hrmEContractTaskActors.setFillStatus(0);
            hrmEContractTaskActors.setSignStatus(0);
            if(actor.getActorType().equals(ActorTypeEnum.CORP.getCode())){
                if(null == corpEmp){
                    throw exception(ErrorCodeConstants.CORP_USER_IS_NULL_ERROR);
                }
                EsignPsnInfo esignPsnInfo = esignPsnInfoMapper.getByPsnId(corpEmp.getEsignPsnId());
                if(ObjUtil.isNotEmpty(esignPsnInfo)){
                    hrmEContractTaskActors.setActorName(esignPsnInfo.getPsnName());
                    hrmEContractTaskActors.setPsnAccount(esignPsnInfo.getPsnAccount());
                }else{
                    hrmEContractTaskActors.setActorName(corpEmp.getName());
                    hrmEContractTaskActors.setPsnAccount(corpEmp.getMobile());
                }
                hrmEContractTaskActors.setCorpId(signFlowParamVo.getCorpId());
                hrmEContractTaskActors.setEmpId(corpEmp.getId());
            } else{
                if(null == employee){
                    throw exception(ErrorCodeConstants.USER_IS_NULL_ERROR);
                }
                EsignPsnInfo esignPsnInfo = esignPsnInfoMapper.getByPsnId(employee.getEsignPsnId());
                if(ObjUtil.isNotEmpty(esignPsnInfo)){
                    hrmEContractTaskActors.setActorName(esignPsnInfo.getPsnName());
                    hrmEContractTaskActors.setPsnAccount(esignPsnInfo.getPsnAccount());
                }else{
                    hrmEContractTaskActors.setActorName(employee.getName());
                    hrmEContractTaskActors.setPsnAccount(employee.getMobile());
                }

                hrmEContractTaskActors.setEmpId(signFlowParamVo.getEmpId());
            }

            actorList.add(hrmEContractTaskActors);
        }
        hrmEContractTaskActorsService.saveBatch(actorList);

        //2.3 添加文件关联
        List<HrmEFile> tempFileList = hrmETempFileService.getFileListByTempId(signFlowParamVo.getTempId());
        List<HrmETaskFile> taskFileList = tempFileList.stream().map(p -> {
            HrmETaskFile hrmETaskFile = new HrmETaskFile();
            BeanUtil.copyProperties(p, hrmETaskFile);
            hrmETaskFile.setTaskId(hrmEContractTask.getId());
            hrmETaskFile.setId(null);
            hrmETaskFile.setDataStatus(1);
            return hrmETaskFile;
        }).collect(Collectors.toList());
        hrmETaskFileService.saveBatch(taskFileList);

        //3. 设置任务控件
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(signFlowParamVo.getTempId());
        List<HrmEEmpComponents> list = hrmEEmpComponentsService.getEmpComponentsList();
        //非劳动合同 过滤归档
        if(hrmEContractTemp.getLabourContract() == 0){
            HrmEEmpComponents hrmEEmpComponents = list.stream().filter(p -> "arc_info".equals(p.getColumnCode())).findAny().orElse(null);
            list = list.stream().filter(p -> p.getId() - hrmEEmpComponents.getId() != 0).filter(p -> p.getColumnParent() - hrmEEmpComponents.getId() != 0).collect(Collectors.toList());
        }
        List<HrmETaskComponents> collect = list.stream().map(p -> {
            HrmETaskComponents hrmETaskComponents = new HrmETaskComponents();
            BeanUtil.copyProperties(p, hrmETaskComponents);
            hrmETaskComponents.setTaskId(hrmEContractTask.getId());
            hrmETaskComponents.setESignTempId(contractTemp.getTempEsignId());
//            hrmETaskComponents.setTenantId(Tenant);
            hrmETaskComponents.setId(null);
            return hrmETaskComponents;
        }).collect(Collectors.toList());

        List<HrmETempComponents> fillInComponents = hrmETempComponentsService.getFillInComponents(contractTemp.getTempEsignId());
        collect.addAll(fillInComponents.stream().map(p -> {
            HrmETaskComponents hrmETaskComponents = new HrmETaskComponents();
            BeanUtil.copyProperties(p, hrmETaskComponents);
            hrmETaskComponents.setTaskId(hrmEContractTask.getId());
            hrmETaskComponents.setESignTempId(contractTemp.getTempEsignId());
            hrmETaskComponents.setId(null);
            return hrmETaskComponents;
        }).collect(Collectors.toList()));
        hrmETaskComponentsService.saveBatch(collect);

        //4. 追加附件
        List<HrmEFile> attachmentList = tempFileList.stream().filter(p -> FileTypeEnums.FILE_ATTACHMENT.getType().equals(p.getType() + "")).collect(Collectors.toList());
        for (HrmEFile hrmEFile : attachmentList) {
            hrmETaskFileService.addSignFlowAttachment(hrmEContractTask.getSignFlowId(),hrmEFile.getEFileId());
        }

        //4. 返回控件
//        List<ComponentResult> result = collect.stream().map(p -> {
//            ComponentResult componentResult = new ComponentResult();
//            BeanUtil.copyProperties(p, componentResult);
//            return componentResult;
//        }).collect(Collectors.toList());
//        getFillInComponents(hrmEContractTask.getId(),)


        //4.获取填写链接
//        String tempEsignId = hrmEContractTemp.getTempEsignId();
//        FillInLinkVo fillInLinkVo = new FillInLinkVo();
//        fillInLinkVo.setDocTemplateId(tempEsignId);
//        fillInLinkVo.setCustomBizNum(hrmEContractTask.getId()+"");
//        JSONObject result = getFillInLink(fillInLinkVo);
//        JSONObject result = new JSONObject();
//        List<ComponentResult> result = new ArrayList<>();
        return hrmEContractTask.getId();
    }

    @TenantIgnore
    @Override
    public void createTaskSignFlowByBpmProcessId(String bpmProcessId,Integer bpmStatus,String message){
        System.out.println("===========================================================消费成功");
        HrmEContractTask contractTask = hrmEContractTaskService.getTaskByProcessId(bpmProcessId);
        if(ObjectUtil.isNull(contractTask)){
            throw exception(ErrorCodeConstants.E_TASK_BPM_PROC_IS_NULL);
        }
        contractTask.setApprovalStatus(bpmStatus);
        contractTask.setProcessMessage(message);
        if(BpmProcessInstanceStatusEnum.APPROVE.getStatus() != bpmStatus){
            hrmEContractTaskService.updateById(contractTask);
            return;
        }
        createTaskSignFlow(contractTask);
    }

    @TenantIgnore
    @Override
    public void createTaskSignFlowByTaskId(Long taskId){
        HrmEContractTask contractTask = hrmEContractTaskService.getById(taskId);
        if(ObjectUtil.isNull(contractTask)){
            throw exception(ErrorCodeConstants.E_TASK_BPM_PROC_IS_NULL);
        }
        createTaskSignFlow(contractTask);
    }

    @TenantIgnore
    @Override
    public void createTaskSignFlow(HrmEContractTask contractTask){
        //1. 校验电子签是否有份额
//        if(!contractPackageService.isUsed(1L)){
//            return;
//        }

        //1. 检测文件是否成功
        try {
            FileUtil.getFileStatus(contractTask.getFilePdfId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2. 获取签署控件位置
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(contractTask.getTempId());
        EsignHttpResponse htmlDetail = getTemplateDetail(contractTemp.getTempEsignId());
        Gson gson = new Gson();
        JsonObject htmlDetailJson = gson.fromJson(htmlDetail.getBody(), JsonObject.class);
        if(htmlDetailJson.get("code").getAsInt() != 0){
            int code = htmlDetailJson.get("code").getAsInt();
            String message = htmlDetailJson.get("message").getAsString();
            throw exception(code,message);
        }
        JsonArray components = htmlDetailJson.get("data").getAsJsonObject().get("components").getAsJsonArray();
        Map<String, JsonObject> componentMap = new HashMap<>();
        for (JsonElement component : components) {
            if(component.getAsJsonObject().get("componentType").getAsInt() != Integer.parseInt(CustomComponentsTypeEnum.SIGN.getCode())){
                continue;
            }
            JsonObject componentPosition = component.getAsJsonObject().get("componentPosition").getAsJsonObject();
            componentMap.put(component.getAsJsonObject().get("componentId").getAsString(),componentPosition);
        }

        //3. 获取签署任务 签署控件
        List<HrmETaskComponents> signComponents = hrmETaskComponentsService.getFillInComponents(contractTask.getId(), CustomComponentsTypeEnum.SIGN.getCode());
        Map<String, List<HrmETaskComponents>> signMap = signComponents.stream().collect(Collectors.groupingBy(HrmETaskComponents::getSignerRole));
        //4. 构建发起数据
        SignFlowCreateVo signFlowCreateBo = new SignFlowCreateVo();
        //4.1 带签署文件
        List<SignFlowCreateVo.DocItem> docs = new ArrayList<>();
        SignFlowCreateVo.DocItem docItem = new SignFlowCreateVo.DocItem();
        //pdf格式文件
        docItem.setFileId(contractTask.getFilePdfId());
        docs.add(docItem);
        signFlowCreateBo.setDocs(docs);

        HrmEContractTemp hrmEContractTemp = hrmEContractTempService.getById(contractTask.getTempId());
        //4.2 流程配置
        SignFlowCreateVo.SignFlowConfig signFlowConfig = new SignFlowCreateVo.SignFlowConfig();
        signFlowConfig.setSignFlowTitle(contractTask.getContractName());
        if(hrmEContractTemp.getSignTime() != 0){
            DateTime dateTime = DateUtil.date(contractTask.getEffectiveDuration());
            signFlowConfig.setSignFlowExpireTime(dateTime.getTime());
        }else{
            DateTime dateTime = DateUtil.offsetDay(new Date(), 89);//最大签署截止时间为90天内
            signFlowConfig.setSignFlowExpireTime(dateTime.getTime());
        }
        //是否自动完结
        signFlowConfig.setAutoFinish(false);
        SignFlowCreateVo.SignFlowConfig.SignConfig signConfig1 = new SignFlowCreateVo.SignFlowConfig.SignConfig();
        signConfig1.setAvailableSignClientTypes("1");
        signFlowConfig.setSignConfig(signConfig1);
        signFlowCreateBo.setSignFlowConfig(signFlowConfig);

        //4.3 签署信息
        List<SignFlowCreateVo.SignerItem> signers = new ArrayList<>();

        List<HrmEContractTaskActors> taskActorList = hrmEContractTaskActorsService.getTaskActorListByTaskId(contractTask.getId());
        for (HrmEContractTaskActors actors : taskActorList) {
            SignFlowCreateVo.SignerItem signerItem = new SignFlowCreateVo.SignerItem();

            SignFlowCreateVo.SignerItem.SignConfig signConfig = new SignFlowCreateVo.SignerItem.SignConfig();
            signConfig.setSignOrder(actors.getActorSignSort());
            signerItem.setSignConfig(signConfig);

            //企业配置
            if(ActorTypeEnum.CORP.getCode().equals(actors.getActorType())){
                signerItem.setSignerType(1);

                List<SignFlowCreateVo.SignerItem.SignFields> signFields = new ArrayList<>();
                //基于多印章 操作
                List<HrmETaskComponents> componentsList = signMap.get(ActorTypeEnum.CORP.getDesc());
                for (HrmETaskComponents hrmETaskComponents : componentsList) {
                    SignFlowCreateVo.SignerItem.SignFields signFieldItem = new SignFlowCreateVo.SignerItem.SignFields();
                    signFieldItem.setFileId(contractTask.getFilePdfId());
//            signFieldItem.setCustomBizNum("xxx123456");
                    SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig normalSignFieldConfig = new SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig();
                    normalSignFieldConfig.setSignFieldStyle(1);
                    normalSignFieldConfig.setFreeMode(false);
                    normalSignFieldConfig.setAutoSign(true);
                    String sealId = getSealId(contractTask.getCorpId());
                    normalSignFieldConfig.setAssignedSealId(sealId);
                    SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig.SignFieldPosition signFieldPosition = new SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig.SignFieldPosition();
                    JsonObject jsonObject = componentMap.get(hrmETaskComponents.getComponentId());
                    signFieldPosition.setPositionX(jsonObject.get("componentPositionX").getAsFloat());
                    signFieldPosition.setPositionY(jsonObject.get("componentPositionY").getAsFloat());
                    signFieldPosition.setPositionPage(jsonObject.get("componentPageNum").getAsInt());
                    normalSignFieldConfig.setSignFieldPosition(signFieldPosition);
                    //自动落章需要注释的参数 -- 开始
//                    SignFlowCreateVo.SignerItem.OrgSignerInfo orgSignerInfo = new SignFlowCreateVo.SignerItem.OrgSignerInfo();
//                    Long corpId = contractTask.getCorpId();
//                    ElecCorp elecCorp = elecCorpMapper.selectById(corpId);
//                    orgSignerInfo.setOrgName(elecCorp.getCorpName());
//                    EmployeeDO employee = employeeService.getEmployeeById(actors.getEmpId());
//                    EsignPsnInfo esignPsnInfo = esignPsnInfoMapper.getByPsnId(employee.getEsignPsnId());
//                    SignFlowCreateVo.SignerItem.OrgSignerInfo.TransactorInfo transactorInfo = new SignFlowCreateVo.SignerItem.OrgSignerInfo.TransactorInfo();
//                    transactorInfo.setPsnAccount(esignPsnInfo.getPsnAccount());
//                    SignFlowCreateVo.SignerItem.OrgSignerInfo.TransactorInfo.PsnInfo psnInfo1 = new SignFlowCreateVo.SignerItem.OrgSignerInfo.TransactorInfo.PsnInfo();
//                    psnInfo1.setPsnName(esignPsnInfo.getPsnName());
//                    transactorInfo.setPsnInfo(psnInfo1);
//                    orgSignerInfo.setTransactorInfo(transactorInfo);
//
//                    signerItem.setOrgSignerInfo(orgSignerInfo);
                    // 自动落章需要注释的参数 -- 结束

                    signFieldItem.setNormalSignFieldConfig(normalSignFieldConfig);
                    signFields.add(signFieldItem);
                }
                signerItem.setSignFields(signFields);
            //员工配置
            }else if(ActorTypeEnum.PERSON.getCode().equals(actors.getActorType())){
                signerItem.setSignerType(0);

                SignFlowCreateVo.SignerItem.SignConfig psnsignConfig = new SignFlowCreateVo.SignerItem.SignConfig();
                psnsignConfig.setSignOrder(actors.getActorSignSort());
                signerItem.setSignConfig(psnsignConfig);

                List<SignFlowCreateVo.SignerItem.SignFields> psnSignFields = new ArrayList<>();
                List<HrmETaskComponents> componentsList = signMap.get(ActorTypeEnum.PERSON.getDesc());
                for (HrmETaskComponents hrmETaskComponents : componentsList) {
                    SignFlowCreateVo.SignerItem.SignFields psnsignFieldItem = new SignFlowCreateVo.SignerItem.SignFields();
                    psnsignFieldItem.setFileId(contractTask.getFilePdfId());
//                psnsignFieldItem.setCustomBizNum("xxx123456");

                    EmployeeDO employee = employeeService.getEmployeeById(actors.getEmpId());
                    EsignPsnInfo esignPsnInfo = esignPsnInfoMapper.getByPsnId(employee.getEsignPsnId());
                    SignFlowCreateVo.SignerItem.PsnSignerInfo psnSignerInfo = new SignFlowCreateVo.SignerItem.PsnSignerInfo();
                    SignFlowCreateVo.SignerItem.PsnSignerInfo.PsnInfo psnInfo = new SignFlowCreateVo.SignerItem.PsnSignerInfo.PsnInfo();
                    if(ObjectUtil.isNull(esignPsnInfo)){
                        psnSignerInfo.setPsnAccount(employee.getMobile());
                        psnInfo.setPsnName(employee.getName());
                    }else{
                        psnSignerInfo.setPsnAccount(esignPsnInfo.getPsnAccount());
                        psnInfo.setPsnName(esignPsnInfo.getPsnName());
                    }

                    psnSignerInfo.setPsnInfo(psnInfo);
                    signerItem.setPsnSignerInfo(psnSignerInfo);

                    SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig psnnormalSignFieldConfig = new SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig();
                    psnnormalSignFieldConfig.setSignFieldStyle(1);
                    SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig.SignFieldPosition position = new SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig.SignFieldPosition();
                    JsonObject jsonObject = componentMap.get(hrmETaskComponents.getComponentId());
                    position.setPositionX(jsonObject.get("componentPositionX").getAsFloat());
                    position.setPositionY(jsonObject.get("componentPositionY").getAsFloat());
                    position.setPositionPage(jsonObject.get("componentPageNum").getAsInt());
                    psnnormalSignFieldConfig.setSignFieldPosition(position);
                    psnsignFieldItem.setNormalSignFieldConfig(psnnormalSignFieldConfig);

                    psnSignFields.add(psnsignFieldItem);

                }
                signerItem.setSignFields(psnSignFields);
            }
            signers.add(signerItem);
        }

        signFlowCreateBo.setSigners(signers);

        String jsonParm = new JSONObject(signFlowCreateBo).toString();

        String apiaddr=ESignUrlConstant.CREATE_SIGN_FLOW;
        //请求方法
        EsignRequestType requestType= EsignRequestType.POST;
        //生成签名鉴权方式的的header
        JsonObject createJson = null;
        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            createJson = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(createJson.get("code").getAsInt() != 0){
            log.error(createJson.get("message").getAsString());
            throw exception(createJson.get("code").getAsInt(),createJson.get("message").getAsString());
        }
        String signFlowId = createJson.get("data").getAsJsonObject().get("signFlowId").getAsString();
        contractTask.setSignFlowId(signFlowId);

        //目前是自动落章  直接写死员工填写
        contractTask.setTaskStatus(TaskStatusEnum.AWAIT_SIGN_PERSON.getCode());

//        contractTask.setApprovalStatus(BpmProcessInstanceStatusEnum.APPROVE.getStatus());
        hrmEContractTaskService.updateById(contractTask);
        //发送消息通知
        inStationSmsService.sendInstationSms(contractTask.getId(),InstationSmsTypeEnum.SIGN.getCode());
        //发送短信通知
        HrmEContractTaskActors personActor = taskActorList.stream().filter(p -> ActorTypeEnum.PERSON.getCode().equals(p.getActorType())).findAny().orElse(null);
        HrmEContractTaskActors corpActor = taskActorList.stream().filter(p -> ActorTypeEnum.CORP.getCode().equals(p.getActorType())).findAny().orElse(null);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("name",corpActor.getActorName());
        jsonObject.set("contractName",contractTask.getContractName());
        jsonObject.set("code",2);
        smsService.sendSignSms(personActor.getPsnAccount(), SmsTempEnum.SIGN.getCode(),jsonObject);
        //扣除份数
        contractPackageService.usedContract(1L);
    }

    @TenantIgnore
    public String getSealId(Long corpId){
        ElecCorp elecCorp = elecCorpMapper.selectById(corpId);
        String s = esignOrgSealMapper.selectSealIdByCorpId(elecCorp.getEsignOrgId());
        return s;
    }

    @Override
    public ComponentBathResult createSignFlowBath(SignFlowParamVo signFlowParamVo) {
        //判断审批
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(signFlowParamVo.getTempId());
        String elec = contractTemp.getLabourContract() == 1?"ELEC_LABOR":"ELEC_OTHER";
        CommonResult<Boolean> booleanCommonResult = bpmNewApi.processCheck(elec);
        if(!booleanCommonResult.getData()){
            throw exception(ErrorCodeConstants.BPM_ERROR);
        }
        System.out.println("发起时审批是否生效==================================");

        List<Long> empIds = signFlowParamVo.getEmpIds();
        ComponentBathResult componentBathResult = new ComponentBathResult();
        List<ComponentBathResult.ColumnValue> columnValues = new ArrayList<>();
        ComponentResult componentResult = null;
        for (Long empId : empIds) {
            //1. 创建任务 获取任务id
            EmployeeDO employee = employeeService.getEmployeeByUserId(empId);
            empId = employee.getId();
            signFlowParamVo.setEmpId(employee.getId());
            Long signFlow = createSignFlow(signFlowParamVo);
            //2. 获取填写表单
            if(componentResult == null){
                componentResult = getFillInComponents(signFlow, ActorTypeEnum.CORP.getCode());
            }

            //3. 创建值列表
            List<ComponentBathResult.ColumnValue> collect = componentResult.getComponentList().stream().map(p -> {
                ComponentBathResult.ColumnValue columnValue1 = new ComponentBathResult.ColumnValue();
                BeanUtil.copyProperties(p,columnValue1);
                columnValue1.setColumnId(p.getId());
                columnValue1.setTaskId(signFlow);
                columnValue1.setColumnValue(p.getComponentValue());
                columnValue1.setTaskColumnId(p.getId());
                return columnValue1;
            }).collect(Collectors.toList());

            /**
             * 循环 taskCom  组件
             * 将 empCom  转为map   通过唯一值  columnCode  为key
             * 拿到empCom的id  作为前端对应值
             * 使用taskCom 的id  作为后端对应值
             *
             *
             *
             */

            List<HrmETaskComponents> taskComponentsList = hrmETaskComponentsService.getFillInComponentsComponentIdIsNull(signFlow);
            List<HrmEEmpComponents> empComponentsList = hrmEEmpComponentsService.getEmpComponentsList();
            Map<String, HrmEEmpComponents> empComponentsMap = empComponentsList.stream().collect(Collectors.toMap(HrmEEmpComponents::getColumnCode, Function.identity()));
            for (HrmETaskComponents hrmETaskComponents : taskComponentsList) {
                ComponentBathResult.ColumnValue columnValue = new ComponentBathResult.ColumnValue();
                HrmEEmpComponents hrmEEmpComponents = empComponentsMap.get(hrmETaskComponents.getColumnCode());
                columnValue.setColumnId(hrmEEmpComponents.getId());
                if(StrUtil.isNotBlank(hrmETaskComponents.getComponentValue())){
                    columnValue.setColumnValue(hrmETaskComponents.getComponentValue());
                }else{
                    if("emp_name".equals(hrmEEmpComponents.getColumnCode())){
                        columnValue.setColumnValue(employee.getName());
                    }else if("contract_name".equals(hrmEEmpComponents.getColumnCode())){
                        HrmEContractTask contractTask = hrmEContractTaskService.getById(signFlow);
                        columnValue.setColumnValue(contractTask.getContractName());
                    }else if("contract_code".equals(hrmEEmpComponents.getColumnCode())){
                        HrmEContractTask contractTask = hrmEContractTaskService.getById(signFlow);
                        columnValue.setColumnValue(getContractCode(contractTask.getTempId(),empId));
                    }
                }
                columnValue.setFillInUpdate(0);
                columnValue.setTaskId(signFlow);
                columnValue.setComponentType(Integer.parseInt(CustomComponentsTypeEnum.TEXT.getCode()));
                columnValue.setTaskColumnId(hrmETaskComponents.getId());
                columnValue.setColumnCode(hrmETaskComponents.getColumnCode());
                collect.add(columnValue);
            }
//            //4. 单独的员工姓名
//
//            //4.1 合同名称
//            HrmEContractTask contractTask = hrmEContractTaskService.getById(signFlow);
//            ComponentBathResult.ColumnValue contractValue = new ComponentBathResult.ColumnValue();
//            contractValue.setColumnId(3L);
//            contractValue.setColumnValue(contractTask.getContractName());
//            contractValue.setFillInUpdate(1);
//            contractValue.setTaskId(signFlow);
//            contractValue.setComponentType(Integer.parseInt(CustomComponentsTypeEnum.TEXT.getCode()));
//            collect.add(1,contractValue);
//            //4.2 合同编号
//            ComponentBathResult.ColumnValue contractCodeValue = new ComponentBathResult.ColumnValue();
//            contractCodeValue.setColumnId(4L);
//            contractCodeValue.setColumnValue(getContractCode(contractTask.getTempId(),empId));
//            contractCodeValue.setFillInUpdate(1);
//            contractCodeValue.setTaskId(signFlow);
//            contractCodeValue.setComponentType(Integer.parseInt(CustomComponentsTypeEnum.TEXT.getCode()));
//            collect.add(2,contractCodeValue);
//
            columnValues.addAll(collect);
        }

        //表头应该不用该
        List<List<ComponentBathResult.Column>> columnResultList = new ArrayList<>();
        //5. 全部固定表头
        List<HrmEEmpComponents> empComponentsList = hrmEEmpComponentsService.getEmpComponentsList();

        //不是劳动合同 过滤掉 合同归档
        if(contractTemp.getLabourContract() == 0){
            empComponentsList = empComponentsList.stream().filter(p -> !"arc_info".equals(p.getColumnCode())).collect(Collectors.toList());
        }
        Map<Long, List<HrmEEmpComponents>> map = empComponentsList.stream().collect(Collectors.groupingBy(HrmEEmpComponents::getColumnParent));
        //6. 一级表头
        List<HrmEEmpComponents> parentColumn = map.get(0L);

        List<ComponentBathResult.Column> columns = recursionColumn(parentColumn, columnResultList, map);
        for (ComponentBathResult.Column column : columns) {
            if("contract_arc".equals(column.getColumnCode())){
                List<ComponentBathResult.Column> collect = componentResult.getComponentList().stream().map(p -> {
                    ComponentBathResult.Column columnSql = new ComponentBathResult.Column();
                    columnSql.setFillInUpdate(1);
//                    if(p.getComponentValue() != null){
//                        columnSql.setFillInUpdate(0);
//                    }
                    columnSql.setComponentType(p.getComponentType());
                    columnSql.setId(p.getId());
                    columnSql.setColumnName(p.getComponentName());
                    return columnSql;
                }).collect(Collectors.toList());
                column.getChildren().addAll(collect);
            }
        }

        componentBathResult.setColumnValueList(columnValues);
        componentBathResult.setColumnList(columns);

        //全部表头
        List<ComponentBathResult.Column> columnList = empComponentsList.stream().map(p -> {
            ComponentBathResult.Column columnSql = new ComponentBathResult.Column();
            columnSql.setId(p.getId());
            columnSql.setColumnName(p.getComponentName());
            return columnSql;
        }).collect(Collectors.toList());
        columnList.addAll(componentResult.getComponentList().stream().map(p -> {
            ComponentBathResult.Column columnSql = new ComponentBathResult.Column();
            columnSql.setId(p.getId());
            columnSql.setColumnName(p.getComponentName());
            return columnSql;
        }).collect(Collectors.toList()));
        Map<Long, ComponentBathResult.Column> columnMap = columnList.stream().collect(Collectors.toMap(ComponentBathResult.Column::getId, Function.identity()));
        Map<Long, List<ComponentBathResult.ColumnValue>> valueMap = columnValues.stream().collect(Collectors.groupingBy(ComponentBathResult.ColumnValue::getTaskId));
        List<Map<Object, Object>> maps = new ArrayList<>();
        for (Long taskId : valueMap.keySet()) {
            Map<Object, Object> resultMap = new HashMap<>();
            List<ComponentBathResult.ColumnValue> valueList = valueMap.get(taskId);
            for (ComponentBathResult.ColumnValue columnValue : valueList) {
                ComponentBathResult.Column column = columnMap.get(columnValue.getColumnId());
                resultMap.put(column.getId(),columnValue.getColumnValue());
            }
            resultMap.put("taskId", valueList.get(0).getTaskId());
            maps.add(resultMap);
        }
        componentBathResult.setColumnValueMap(maps);


        return componentBathResult;
    }

    @Override
    public ComponentBathResult getFillInData(Long taskId) {
        HrmEContractTask contractTask = hrmEContractTaskService.getById(taskId);
        HrmEContractTaskActors taskActors = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.PERSON.getCode());
        ComponentBathResult componentBathResult = new ComponentBathResult();
        List<ComponentBathResult.ColumnValue> columnValues = new ArrayList<>();

        EmployeeDO employee = employeeService.getEmployeeById(taskActors.getEmpId());
        ComponentResult componentResult = getFillInComponents(taskId, ActorTypeEnum.CORP.getCode());

        //3. 创建值列表
        List<ComponentBathResult.ColumnValue> collect = componentResult.getComponentList().stream().map(p -> {
            ComponentBathResult.ColumnValue columnValue1 = new ComponentBathResult.ColumnValue();
            BeanUtil.copyProperties(p,columnValue1);
            columnValue1.setColumnId(p.getId());
            columnValue1.setTaskId(taskId);
            columnValue1.setColumnValue(p.getComponentValue());
            columnValue1.setTaskColumnId(p.getId());
            return columnValue1;
        }).collect(Collectors.toList());

        List<HrmETaskComponents> taskComponentsList = hrmETaskComponentsService.getFillInComponentsComponentIdIsNull(taskId);
        List<HrmEEmpComponents> empComponentsList = hrmEEmpComponentsService.getEmpComponentsList();
        Map<String, HrmEEmpComponents> empComponentsMap = empComponentsList.stream().collect(Collectors.toMap(HrmEEmpComponents::getColumnCode, Function.identity()));
        for (HrmETaskComponents hrmETaskComponents : taskComponentsList) {
            ComponentBathResult.ColumnValue columnValue = new ComponentBathResult.ColumnValue();
            HrmEEmpComponents hrmEEmpComponents = empComponentsMap.get(hrmETaskComponents.getColumnCode());
            columnValue.setColumnId(hrmEEmpComponents.getId());
            if(StrUtil.isNotBlank(hrmETaskComponents.getComponentValue())){
                columnValue.setColumnValue(hrmETaskComponents.getComponentValue());
            }else{
                if("emp_name".equals(hrmEEmpComponents.getColumnCode())){
                    columnValue.setColumnValue(employee.getName());
                }else if("contract_name".equals(hrmEEmpComponents.getColumnCode())){
                    columnValue.setColumnValue(contractTask.getContractName());
                }else if("contract_code".equals(hrmEEmpComponents.getColumnCode())){
                    columnValue.setColumnValue(getContractCode(contractTask.getTempId(),taskId));
                }
            }
            columnValue.setFillInUpdate(0);
            columnValue.setTaskId(taskId);
            columnValue.setComponentType(Integer.parseInt(CustomComponentsTypeEnum.TEXT.getCode()));
            columnValue.setTaskColumnId(hrmETaskComponents.getId());
            columnValue.setColumnCode(hrmETaskComponents.getColumnCode());
            collect.add(columnValue);
        }
        columnValues.addAll(collect);

        //表头应该不用该
        List<List<ComponentBathResult.Column>> columnResultList = new ArrayList<>();
        //5. 全部固定表头
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(contractTask.getTempId());
        //不是劳动合同 过滤掉 合同归档
        if(contractTemp.getLabourContract() == 0){
            empComponentsList = empComponentsList.stream().filter(p -> !"arc_info".equals(p.getColumnCode())).collect(Collectors.toList());
        }
        Map<Long, List<HrmEEmpComponents>> map = empComponentsList.stream().collect(Collectors.groupingBy(HrmEEmpComponents::getColumnParent));
        //6. 一级表头
        List<HrmEEmpComponents> parentColumn = map.get(0L);

        List<ComponentBathResult.Column> columns = recursionColumn(parentColumn, columnResultList, map);
        for (ComponentBathResult.Column column : columns) {
            if("contract_arc".equals(column.getColumnCode())){
                List<ComponentBathResult.Column> collect1 = componentResult.getComponentList().stream().map(p -> {
                    ComponentBathResult.Column columnSql = new ComponentBathResult.Column();
                    columnSql.setFillInUpdate(1);
                    if(p.getComponentValue() != null){
                        columnSql.setFillInUpdate(0);
                    }
                    columnSql.setComponentType(p.getComponentType());
                    columnSql.setId(p.getId());
                    columnSql.setColumnName(p.getComponentName());
                    return columnSql;
                }).collect(Collectors.toList());
                column.getChildren().addAll(collect1);
            }
        }

        componentBathResult.setColumnValueList(columnValues);
        componentBathResult.setColumnList(columns);

        //全部表头
        List<ComponentBathResult.Column> columnList = empComponentsList.stream().map(p -> {
            ComponentBathResult.Column columnSql = new ComponentBathResult.Column();
            columnSql.setId(p.getId());
            columnSql.setColumnName(p.getComponentName());
            return columnSql;
        }).collect(Collectors.toList());
        columnList.addAll(componentResult.getComponentList().stream().map(p -> {
            ComponentBathResult.Column columnSql = new ComponentBathResult.Column();
            columnSql.setId(p.getId());
            columnSql.setColumnName(p.getComponentName());
            return columnSql;
        }).collect(Collectors.toList()));
        Map<Long, ComponentBathResult.Column> columnMap = columnList.stream().collect(Collectors.toMap(ComponentBathResult.Column::getId, Function.identity()));
        Map<Long, List<ComponentBathResult.ColumnValue>> valueMap = columnValues.stream().collect(Collectors.groupingBy(ComponentBathResult.ColumnValue::getTaskId));
        List<Map<Object, Object>> maps = new ArrayList<>();
        for (Long taskIdKey : valueMap.keySet()) {
            Map<Object, Object> resultMap = new HashMap<>();
            List<ComponentBathResult.ColumnValue> valueList = valueMap.get(taskIdKey);
            for (ComponentBathResult.ColumnValue columnValue : valueList) {
                ComponentBathResult.Column column = columnMap.get(columnValue.getColumnId());
                resultMap.put(column.getId(),columnValue.getColumnValue());
            }
            resultMap.put("taskId", valueList.get(0).getTaskId());
            maps.add(resultMap);
        }
        componentBathResult.setColumnValueMap(maps);


        return componentBathResult;
    }


    public List<ComponentBathResult.Column> recursionColumn(List<HrmEEmpComponents> empComponentsList,List<List<ComponentBathResult.Column>> columnResultList,Map<Long, List<HrmEEmpComponents>> map){
        List<ComponentBathResult.Column> columns = new ArrayList<>();
        for (HrmEEmpComponents hrmEEmpComponents : empComponentsList) {
            ComponentBathResult.Column columnItem = new ComponentBathResult.Column();
            columnItem.setFillInUpdate(hrmEEmpComponents.getFillInUpdate());
            columnItem.setRequired(hrmEEmpComponents.getRequired());
            columnItem.setComponentType(hrmEEmpComponents.getComponentType());
            columnItem.setId(hrmEEmpComponents.getId());
            columnItem.setColumnName(hrmEEmpComponents.getComponentName());
            columnItem.setColumnCode(hrmEEmpComponents.getColumnCode());
            if(CustomComponentsTypeEnum.SELECT.getCode().equals(hrmEEmpComponents.getComponentType()+"") && "contract_type".equals(hrmEEmpComponents.getColumnCode())){
                ArrayList<Map<String,Object>> strings = new ArrayList<>();
                Map<String, Object> selectOptionMap = new HashMap<>();
//                selectOptionMap.put("1","固定期限劳动合同");
//                selectOptionMap.put("2","无固定期限劳动合同");
//                selectOptionMap.put("3","以完成一定工作任务为期限的劳动合同");
                selectOptionMap.put("id","1");
                selectOptionMap.put("name","固定期限劳动合同");
                strings.add(selectOptionMap);
                selectOptionMap = new HashMap<>();
                selectOptionMap.put("id","2");
                selectOptionMap.put("name","无固定期限劳动合同");
                strings.add(selectOptionMap);
                selectOptionMap = new HashMap<>();
                selectOptionMap.put("id","3");
                selectOptionMap.put("name","以完成一定工作任务为期限的劳动合同");
                strings.add(selectOptionMap);
                columnItem.setSelectOption(strings);
            }else if(CustomComponentsTypeEnum.SELECT.getCode().equals(hrmEEmpComponents.getComponentType()+"") && "contract_time".equals(hrmEEmpComponents.getColumnCode())){
                ArrayList<Map<String,Object>> strings = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                    Map<String, Object> selectOptionMap = new HashMap<>();
                    selectOptionMap.put("id",(i+1)+"");
                    selectOptionMap.put("name",(i+1)+"年");
                    strings.add(selectOptionMap);
                }
                columnItem.setSelectOption(strings);
            }
            List<HrmEEmpComponents> children = map.get(hrmEEmpComponents.getId());
            if(CollUtil.isNotEmpty(children)){
                columnItem.setChildren(recursionColumn(children, columnResultList, map));
            }
            columns.add(columnItem);
            columnResultList.add(columns);
        }
        return columns;
    }

    @Override
    @DataPermission(enable = false)
    public String getSignFlowLink(Long taskId,String actorType,String redirectUrl) {
        HrmEContractTask contractTask = hrmEContractTaskService.getById(taskId);
        if(StrUtil.isEmpty(contractTask.getSignFlowId())){
            //1. 校验电子签是否有份额
            if(!contractPackageService.isUsed(1L)){
                throw exception(ErrorCodeConstants.E_SIGN_CONTRACT_NUM_ERROR);
            }
            //2. 创建任务
            createTaskSignFlowByTaskId(taskId);
        }

        String apiaddr=String.format(ESignUrlConstant.SIGN_FLOW_LINK,contractTask.getSignFlowId());
        //请求方法
        EsignRequestType requestType= EsignRequestType.POST;

        List<HrmEContractTaskActors> actorsList = hrmEContractTaskActorsService.getTaskActorListByTaskId(taskId);
        HrmEContractTaskActors hrmEContractTaskActors = actorsList.stream().filter(p -> p.getActorType().equals(actorType)).findAny().orElse(null);
//        if(StrUtil.isNotBlank(hrmEContractTaskActors.getSignUrl())){
//            return hrmEContractTaskActors.getSignUrl();
//        }

        //获取文件id以及文件上传地址
        JSONObject parram = new JSONObject();
        //是否需要登录
        parram.set("needLogin",false);

        if(TaskStatusEnum.ACCOMPLISH.getCode() == contractTask.getTaskStatus()){
            parram.set("urlType",1);
        }
        if(ActorTypeEnum.CORP.getCode().equals(actorType)){
            ElecCorpDetailVo elecCorpDetailVo = elecCorpMapper.selectElecCorpDetail(contractTask.getCorpId());
            JSONObject organization = new JSONObject();
//        17684726605  13220866005
            organization.set("orgId",elecCorpDetailVo.getOrgId());
            parram.set("organization",organization);
        }else{
            JSONObject operator = new JSONObject();
//        17684726605  13220866005
            operator.set("psnAccount",hrmEContractTaskActors.getPsnAccount());
            parram.set("operator",operator);
        }


        if(StrUtil.isNotBlank(redirectUrl)){
            JSONObject redirectConfig = new JSONObject();
            redirectConfig.set("redirectUrl",redirectUrl);
            parram.set("redirectConfig",redirectConfig);
        }

        String jsonParm=parram.toString();


        //生成签名鉴权方式的的header
        JsonObject jsonObject = null;
        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            Gson gson = new Gson();
            jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        if(jsonObject.get("code").getAsInt() == 1435002){
            throw exception(ErrorCodeConstants.EMP_SIGN_PHONE_ERROR);
        }
        if(jsonObject.get("code").getAsInt() != 0){
            throw exception(ErrorCodeConstants.E_SIGN_API_ERROR);
        }
        String url = jsonObject.get("data").getAsJsonObject().get("url").getAsString();
        hrmEContractTaskActors.setSignUrl(url);
        hrmEContractTaskActorsService.updateById(hrmEContractTaskActors);
        return url;
    }

    @Override
    public String getTaskSignStatus(Long taskId,String type) {
        HrmEContractTaskActors taskActors = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, type);
        return taskActors.getSignStatus()+"";
    }

    @Override
    public String updateSignRegion(HrmESignRegionParam param) {
        HrmEContractTask contractTask = hrmEContractTaskService.getById(param.getTaskId());
        //获取文件id以及文件上传地址
        String signFlowId = contractTask.getSignFlowId();
        JSONObject parram = new JSONObject();
        String jsonParm=parram.toString();
        EsignRequestType requestType= EsignRequestType.GET;
        String apiaddr=String.format(ESignUrlConstant.SIGN_FLOW_DETAIL,signFlowId);
        //生成签名鉴权方式的的header
        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
            System.out.println(jsonObject.toString());
            if(jsonObject.get("code").getAsInt() != 0){
                throw exception(ErrorCodeConstants.E_SIGN_API_ERROR);
            }
            JsonArray signers = jsonObject.get("data").getAsJsonObject().get("signers").getAsJsonArray();
            for (JsonElement jsonElement : signers) {
                JsonObject asJsonObject = jsonElement.getAsJsonObject();

                if(!asJsonObject.get("psnSigner").isJsonNull() && asJsonObject.get("psnSigner").getAsJsonObject() != null){
                    removeSign(asJsonObject,signFlowId);
                    addSign(asJsonObject,signFlowId,param.getPhone(),param.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //修改数据库参与方
        HrmEContractTaskActors personActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(param.getTaskId(), ActorTypeEnum.PERSON.getCode());
        personActor.setPsnAccount(param.getPhone());
        personActor.setActorName(param.getName());
        hrmEContractTaskActorsService.updateById(personActor);
        return null;
    }


    public static void main(String[] args) {
        DateTime startTime = DateUtil.parse("2024-08-21 00:00:00");
        int i = 1;
        DateTime contractEndTime = DateUtil.offsetMonth(startTime,12 * i);
        System.out.println("startTime:"+startTime+"========="+DateUtil.compare(startTime, new Date()));
        System.out.println("contractEndTime:"+contractEndTime+"========="+DateUtil.compare(contractEndTime, new Date()));


        String status = "";
        int i1 = contractEndTime.compareTo(new Date());
        System.out.println(i1);
        if (DateUtil.compare(startTime, new Date()) > 0) {
            status = "未执行";
        } else if (DateUtil.compare(contractEndTime, new Date()) < 0) {
            status = "已过期";
        } else {
            status = "执行中";
        }
        System.out.println("status:"+status);

//        HashMap<Object, Object> map = new HashMap<>();
//        map.put("1951530101905014786","123");
//        Long id = 1951530101905014786L;
//        Long finalContractStartTimeId = id;
//        Object o = map.get(finalContractStartTimeId.toString());
//        System.out.println(o.toString());
//        String esignUrl = "https://smlopenapi.esign.cn";
//        //获取文件id以及文件上传地址
//        String signFlowId = "34bda66faf714a0ba4050399a9a4421b";
//        JSONObject parram = new JSONObject();
//        String jsonParm=parram.toString();
//        EsignRequestType requestType= EsignRequestType.GET;
//        String apiaddr=String.format(ESignUrlConstant.SIGN_FLOW_DETAIL,signFlowId);
//        //生成签名鉴权方式的的header
//        try {
//            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
//            Gson gson = new Gson();
//            JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
//            System.out.println(jsonObject.toString());
//            if(jsonObject.get("code").getAsInt() != 0){
//                throw exception(ErrorCodeConstants.E_SIGN_API_ERROR);
//            }
//            JsonArray signers = jsonObject.get("data").getAsJsonObject().get("signers").getAsJsonArray();
//            for (JsonElement jsonElement : signers) {
//                JsonObject asJsonObject = jsonElement.getAsJsonObject();
//
//                if(!asJsonObject.get("psnSigner").isJsonNull() && asJsonObject.get("psnSigner").getAsJsonObject() != null){
//                    removeSign(asJsonObject,signFlowId);
//                    addSign(asJsonObject,signFlowId);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public static void addSign(JsonObject asJsonObject,String signFlowId,String phone,String name){
        String esignUrl = "https://smlopenapi.esign.cn";
        List<SignFlowCreateVo.SignerItem> signerItems = new ArrayList<>();
        SignFlowCreateVo.SignerItem signerItem = new SignFlowCreateVo.SignerItem();
        SignFlowCreateVo.SignerItem.SignConfig psnsignConfig = new SignFlowCreateVo.SignerItem.SignConfig();
        psnsignConfig.setSignOrder(asJsonObject.get("signOrder").getAsInt());
        signerItem.setSignConfig(psnsignConfig);
        signerItem.setSignerType(0);

        SignFlowCreateVo.SignerItem.PsnSignerInfo psnSignerInfo = new SignFlowCreateVo.SignerItem.PsnSignerInfo();
        psnSignerInfo.setPsnAccount(phone);
        SignFlowCreateVo.SignerItem.PsnSignerInfo.PsnInfo psnInfo = new SignFlowCreateVo.SignerItem.PsnSignerInfo.PsnInfo();
        psnInfo.setPsnName(name);
        psnSignerInfo.setPsnInfo(psnInfo);
        signerItem.setPsnSignerInfo(psnSignerInfo);

        JsonArray signFields = asJsonObject.get("signFields").getAsJsonArray();
        List<SignFlowCreateVo.SignerItem.SignFields> signFieldsResult = new ArrayList<>();
        for (JsonElement signField : signFields) {
            if(signField.getAsJsonObject().get("signFieldType").getAsInt() == 0){
                //签署区
                SignFlowCreateVo.SignerItem.SignFields signFields1 = new SignFlowCreateVo.SignerItem.SignFields();
                signFields1.setFileId(signField.getAsJsonObject().get("fileId").getAsString());
//                signFields1.setSignFieldType(0);
                SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig normalSignFieldConfig = new SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig();
                SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig.SignFieldPosition position = new SignFlowCreateVo.SignerItem.SignFields.NormalSignFieldConfig.SignFieldPosition();

                JsonObject positionJson = signField.getAsJsonObject().get("normalSignFieldConfig").getAsJsonObject().get("signFieldPosition").getAsJsonObject();
                position.setPositionX(positionJson.get("positionX").getAsFloat());
                position.setPositionY(positionJson.get("positionY").getAsFloat());
                position.setPositionPage(positionJson.get("positionPage").getAsInt());
                normalSignFieldConfig.setSignFieldPosition(position);
                normalSignFieldConfig.setSignFieldStyle(1);
                signFields1.setNormalSignFieldConfig(normalSignFieldConfig);
                signFieldsResult.add(signFields1);
            }
        }
        signerItem.setSignFields(signFieldsResult);
        signerItems.add(signerItem);


        //获取文件id以及文件上传地址
        JSONObject parram = new JSONObject();
        parram.set("identityVerify",false);
        parram.set("signers",signerItems);
        String jsonParm=parram.toString();
        EsignRequestType requestType= EsignRequestType.POST;
        String apiaddr=String.format(ESignUrlConstant.ADD_SIGN_FLOW,signFlowId);
        //生成签名鉴权方式的的header
        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
            System.out.println("添加:"+apiaddr);
            System.out.println(jsonObject.toString());
            if(jsonObject.get("code").getAsInt() != 0){
                throw exception(ErrorCodeConstants.E_SIGN_API_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //修改签署人信息

    }

    public static void removeSign(JsonObject asJsonObject,String signFlowId){
        List<String> signFieldId = new ArrayList<>();
        JsonArray signFields = asJsonObject.get("signFields").getAsJsonArray();
        for (JsonElement signField : signFields) {
            if(signField.getAsJsonObject().get("signFieldType").getAsInt() == 0){
                signFieldId.add(signField.getAsJsonObject().get("signFieldId").getAsString());
            }
        }
        if(CollUtil.isEmpty(signFieldId)){
            return;
        }
        String esignUrl = "https://smlopenapi.esign.cn";
        //获取文件id以及文件上传地址
        JSONObject parram = new JSONObject();
        String jsonParm=parram.toString();
        EsignRequestType requestType= EsignRequestType.DELETE;
        String apiaddr=String.format(ESignUrlConstant.REMOVE_SIGN_FLOW,signFlowId,String.join(",", signFieldId));
        //生成签名鉴权方式的的header
        System.out.println("删除："+apiaddr);
        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
            if(jsonObject.get("code").getAsInt() != 0){
                throw exception(ErrorCodeConstants.E_SIGN_API_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public ComponentBathParam getContractTimeAndStatus(ComponentBathParam param) {
        List<ComponentBathParam.Column> columnList = param.getColumnList();
        Long contractTimeId = null;
        Long contractStartTimeId = null;
        Long contractEndTime1 = null;
        Long contractStatus = null;
        for (ComponentBathParam.Column column : columnList) {
            if(!"arc_info".equals(column.getColumnCode())){
                continue;
            }
            for (ComponentBathParam.Column child : column.getChildren()) {
                if("contract_time".equals(child.getColumnCode())){
                    contractTimeId = child.getId();
                }
                if("contract_start_time".equals(child.getColumnCode())){
                    contractStartTimeId = child.getId();
                }
                if("contract_end_time1".equals(child.getColumnCode())){
                    contractEndTime1 = child.getId();
                }
                if("contract_status".equals(child.getColumnCode())){
                    contractStatus = child.getId();
                }
            }

        }

        Long finalContractTimeId = contractTimeId;
        Long finalContractStartTimeId = contractStartTimeId;
        Long finalContractEndTime = contractEndTime1;
        Long finalContractStatus = contractStatus;
        List<Map<Object, Object>> collect = param.getColumnValueMap().stream().peek(p -> {
                String contractTime = (String) p.get(finalContractTimeId.toString());
                String contractStartTime = (String) p.get(finalContractStartTimeId.toString());
                if(StrUtil.isNotBlank(contractStartTime) && StrUtil.isNotBlank(contractTime)){
                    DateTime startTime = DateUtil.parse(contractStartTime, DatePattern.NORM_DATE_PATTERN);
                    DateTime contractEndTime = DateUtil.offsetMonth(startTime, 12 * Integer.parseInt(contractTime));
                    contractEndTime = DateUtil.offsetDay(contractEndTime, -1);
                    HashMap<String, Object> mapResult = new HashMap<>();
                    mapResult.put("contractEndTime", contractEndTime);
                    String status = "";
                    if (DateUtil.compare(contractEndTime, new Date()) < 1) {
                        status = "已到期";
                    } else if (DateUtil.compare(startTime, new Date()) > 1) {
                        status = "未执行";
                    } else {
                        status = "执行中";
                    }

                    p.put(finalContractEndTime, DateUtil.format(contractEndTime,DatePattern.NORM_DATE_PATTERN));
                    p.put(finalContractStatus, status);
                }

        }).collect(Collectors.toList());

        param.setColumnValueMap(collect);

        return param;
    }




    @Override
    public String getContractCode(Long tempId,Long empId) {
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(tempId);

        Integer existNumber = contractTemp.getExistNumber();
        if(existNumber == 0){
            return "";
        }
        Integer numCreateRule = contractTemp.getNumCreateRule();
        if(numCreateRule == 1){
            return "";
        }

        //1. 固定编码
        String fixedCode = contractTemp.getFixedCode();
        //2. 编号日期格式
        String codeTime = contractTemp.getCodeTime();

        StringBuilder contractCode = new StringBuilder();
        List<HrmEContractCode> hrmEContractCodes = hrmEContractCodeService.getContractCodeBytempId(tempId);
        for (HrmEContractCode hrmEContractCode : hrmEContractCodes) {
            if(hrmEContractCode.getSelected() == 0){
                continue;
            }
            if(hrmEContractCode.getCode().equals(ContractCodeEnum.FIXED_CODE.getCode())){
                contractCode.append(fixedCode);
            }
            if(hrmEContractCode.getCode().equals(ContractCodeEnum.CODE_TIME.getCode())){
                contractCode.append(DateUtil.format(new Date(),codeTime));
            }
            if(hrmEContractCode.getCode().equals(ContractCodeEnum.EMP_NO.getCode())){
                EmployeeDO employee = employeeService.getEmployeeById(empId);
                contractCode.append(employee.getEmployeeNo());
            }
        }
        return contractCode.toString();
    }

    @Override
    public boolean revokeTask(Long taskId,String revokeReason) {
        HrmEContractTask task = hrmEContractTaskService.getById(taskId);
        //1. 修改库状态
        task.setTaskStatus(TaskStatusEnum.REVOCATION.getCode());
        task.setRevokeReason(revokeReason);
        hrmEContractTaskService.updateById(task);

        //2. 撤回e钱宝签署
//        EsignRequestType requestType= EsignRequestType.POST;
//        JSONObject parram = new JSONObject();
//        String jsonParm=parram.toString();
//        String url = String.format(ESignUrlConstant.SIGN_FLOW_REVOKE,task.getSignFlowId());
//        EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, url, esignUrl);
//        Gson gson = new Gson();
//        JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
//        if(jsonObject.get("code").getAsInt() != 0){
//            throw exception(ErrorCodeConstants.E_SIGN_API_ERROR);
//        }
        return Boolean.TRUE;
    }

    @Override
    public boolean removeTask(Long taskId) {
        HrmEContractTask task = hrmEContractTaskService.getById(taskId);
        //1. 修改库状态
        task.setDataStatus(0);
        hrmEContractTaskService.updateById(task);
        return Boolean.TRUE;
    }

    @Override
    public boolean urgeTask(Long taskId) {
        //发送短信和站内信通知
        HrmEContractTask hrmEContractTask = hrmEContractTaskService.getById(taskId);
        HrmEContractTaskActors taskActors = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.PERSON.getCode());
        HrmEContractTaskActors corpActor = hrmEContractTaskActorsService.getTaskActorListByTaskIdAndActorType(taskId, ActorTypeEnum.CORP.getCode());
        if(TaskStatusEnum.AWAIT_FILL_IN_PERSON.getCode() == hrmEContractTask.getTaskStatus()){
            inStationSmsService.sendInstationSms(taskId,InstationSmsTypeEnum.URGE_FILLIN.getCode());

            JSONObject jsonObject = new JSONObject();
            jsonObject.set("name",corpActor.getActorName());
            jsonObject.set("contractName",hrmEContractTask.getContractName());
            jsonObject.set("code",0);
            smsService.sendSignSms(taskActors.getPsnAccount(),SmsTempEnum.URGE_FILLIN.getCode(),jsonObject);
        }else if(TaskStatusEnum.AWAIT_SIGN_PERSON.getCode() == hrmEContractTask.getTaskStatus()){
            inStationSmsService.sendInstationSms(taskId,InstationSmsTypeEnum.URGE_SIGN.getCode());

            JSONObject jsonObject = new JSONObject();
            jsonObject.set("name",corpActor.getActorName());
            jsonObject.set("contractName",hrmEContractTask.getContractName());
            jsonObject.set("time",DateUtil.format(hrmEContractTask.getEffectiveDuration(),DatePattern.NORM_DATETIME_PATTERN));
            jsonObject.set("code",2);
            smsService.sendSignSms(taskActors.getPsnAccount(),SmsTempEnum.URGE_SIGN.getCode(),jsonObject);
        }

        return Boolean.TRUE;
    }

    @Override
    public JSONObject getTaskDetail(Long taskId) {
        HrmEContractTask hrmEContractTask = hrmEContractTaskService.getById(taskId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("taskId",taskId);
        jsonObject.set("corpId",hrmEContractTask.getCorpId());
        jsonObject.set("tempId",hrmEContractTask.getTempId());
        List<HrmEContractTaskActors> taskActorsList = hrmEContractTaskActorsService.getTaskActorListByTaskId(taskId);
        HrmEContractTaskActors hrmEContractTaskActors = taskActorsList.stream().filter(p -> p.getActorType().equals(ActorTypeEnum.PERSON.getCode())).findAny().orElse(null);
        if(hrmEContractTaskActors != null){
            List<Long> longs = new ArrayList<>();
            EmployeeDO employee = employeeService.getEmployeeById(hrmEContractTaskActors.getEmpId());
            Long userId = employee.getUserId();
            longs.add(userId);
            jsonObject.set("empIds",longs);
            jsonObject.set("empId",userId);
        }
        return jsonObject;
    }

    @Override
    public List<JSONObject> getTempNameList(String tempName) {
        HrmEContractTempParam param = new HrmEContractTempParam();
        param.setTempName(tempName);
        param.setTempStatus(1);
        PageResult<HrmEContractTempResult> docTempPage = hrmEContractTempService.getDocTempPage(param);
        List<JSONObject> collect = docTempPage.getList().stream().map(p -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("tempId", p.getId());
            jsonObject.set("tempName", p.getTempName());
            return jsonObject;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public JSONObject getTempDetailToTask(Long tempId) {
        JSONObject jsonObject = new JSONObject();
        List<HrmEFile> fileList = hrmETempFileService.getFileListByTempId(tempId);
        List<HrmEFile> fileSignList = fileList.stream().filter(p -> FileTypeEnums.FILE_SIGN.getType().equals(p.getType() + "")).collect(Collectors.toList());
        List<HrmEFile> fileAttachmentList = fileList.stream().filter(p -> FileTypeEnums.FILE_ATTACHMENT.getType().equals(p.getType() + "")).collect(Collectors.toList());
        jsonObject.set("tempId",tempId);
        jsonObject.set("fileSignList",fileSignList);
        jsonObject.set("fileAttachmentList",fileAttachmentList);
        return jsonObject;
    }

    @Override
    public PageResult<HrmETaskListResult> getTaskAppPage(HrmEContractTaskParam param) {
        return hrmEContractTaskService.getTaskAppPage(param);
    }

    @Override
    public String getFillInViewToPDFApp(ComponentResult param) {
        Long taskId = param.getTaskId();
        HrmEContractTask contractTask = hrmEContractTaskService.getById(taskId);
        HrmEContractTemp contractTemp = hrmEContractTempService.getById(contractTask.getTempId());
        List<HrmETaskComponents> fillInComponents = hrmETaskComponentsService.getFillInComponents(taskId);
        Map<Long, HrmETaskComponents> componentsMap = fillInComponents.stream().collect(Collectors.toMap(HrmETaskComponents::getId, Function.identity()));
        String apiaddr=ESignUrlConstant.TEMPLATE_TO_PDF;
        String tempId = contractTemp.getTempEsignId();
        String fileName = UUID.randomUUID().toString();
        //请求方法
        EsignRequestType requestType= EsignRequestType.POST;

        //获取文件id以及文件上传地址
        JSONObject parram = new JSONObject();
        parram.set("docTemplateId",tempId);
        parram.set("fileName",fileName);
        JSONArray components = new JSONArray();
        List<ComponentResult.Component> componentList = param.getComponentList();
        for (ComponentResult.Component component : componentList) {
            HrmETaskComponents hrmETaskComponents = componentsMap.get(component.getId());
            if(hrmETaskComponents == null ||(hrmETaskComponents.getComponentId() == null && hrmETaskComponents.getComponentKey() == null)){
                continue;
            }
            JSONObject comItem = new JSONObject();
            comItem.set("componentId",hrmETaskComponents.getComponentId());
            comItem.set("componentKey",hrmETaskComponents.getComponentKey());
            comItem.set("componentValue",StrUtil.isNotBlank(component.getComponentValue())?component.getComponentValue():"--");
            components.add(comItem);
        }

        parram.set("components",components);
        parram.set("requiredCheck",false);
        String jsonParm=parram.toString();



        try {
            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
            if(jsonObject.get("code").getAsInt() != 0){
                throw exception(jsonObject.get("code").getAsInt(),jsonObject.get("message").getAsString());
            }
//          // 转文件  获取文件地址
            return FileUtil.getFileHTMLFileDownloadUrl(jsonObject.get("data").getAsJsonObject().get("fileId").getAsString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}
